#include "LutVtkXmlFile.h"
#include "iostream"
#include "tinyxml.h"

using namespace tinyxml;

void
LutVtkXmlFile::open(std::string filename)
{
    TiXmlDocument doc(filename.c_str());
    if(!doc.LoadFile()){
            std::cerr << "error #" << doc.ErrorId() << " : " << doc.ErrorDesc()
                      << std::endl;
    }
    else{
        m_filename=filename;
    }
}

boost::shared_ptr<LutModel>
LutVtkXmlFile::loadLut()
{

    boost::shared_ptr<LutModel> lutmodel_ptr=boost::shared_ptr<LutModel>() ;
    TiXmlDocument doc(m_filename.c_str());
    if(!doc.LoadFile()){
            std::cerr<< "erreur lors du chargement" << std::endl;
            std::cerr << "error #" << doc.ErrorId() << " : " << doc.ErrorDesc()
                      << std::endl;
    }
    // read file
    TiXmlHandle hdl(&doc);
    TiXmlElement* pElem;
    pElem=hdl.FirstChild("ColorMap").Element();
    if(!pElem){
       std::cout << " ColorMap node doesn't exist " << std::endl;
       return lutmodel_ptr;
    }
    std::string colorspace = pElem->Attribute("space");
    if(colorspace == "RGB")
    {
        lutmodel_ptr = boost::shared_ptr<LutModel> (new LutModel(rgb_cs) );
    }
    else if(colorspace == "HSV")
    {
         lutmodel_ptr = boost::shared_ptr<LutModel> (new LutModel(hsv_cs) );
    }
    else
    {
        std::cout << " wrong att systemeCouleur " << std::endl;
        return lutmodel_ptr;
    }

    lutmodel_ptr->setInterpolatorType(BoundInterpolator::linear);

   //---child bound nodes
    TiXmlElement *elem = hdl.FirstChildElement().FirstChildElement().Element();
    if(!elem){
       std::cout << " point node doesn't exist " << std::endl;
    }
    while (elem){
        double point_x;
        elem->QueryDoubleAttribute("x",&point_x);
        int channel1,channel2,channel3;
        elem->QueryIntAttribute("r", &channel1);
        elem->QueryIntAttribute("g", &channel2);
        elem->QueryIntAttribute("g", &channel3);
        lutmodel_ptr->addBound(point_x,channel1,channel2, channel3 );
        elem = elem->NextSiblingElement();
    }
    return lutmodel_ptr;
}

void
LutVtkXmlFile::saveAs( const boost::shared_ptr<LutModel> lut_ptr ,
                       std::string filename)
{
    //  creation d'un nouveau document xml
    TiXmlDocument doc;
    //  ecriture de l'en-tête
    TiXmlElement* msg;
    TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
    doc.LinkEndChild( decl );
    //
    doc.SaveFile(filename.c_str() ); // enregistrement du fichier exporté
}

